﻿using Microsoft.Extensions.Hosting;
using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using VisionCloud.Utility;

namespace VisionCloud.Web.Service
{
    /// <summary>
    /// 定时删除日志文件服务
    /// </summary>
    public class DeleteLogFileService : BackgroundService
    {
        //日志文件存储路径（注意linux容器下的映射路径）
        private static readonly string logFileDir = ConfigHelper.GetValue<string>("LogFileDirectory");

        private static readonly int logFileExpireDay = ConfigHelper.GetValue<int>("LogFileExpireDay");

        /// <summary>
        /// 后台执行任务
        /// </summary>
        /// <param name="stoppingToken"></param>
        /// <returns></returns>
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                if (!Directory.Exists(logFileDir))
                {
                    Directory.CreateDirectory(logFileDir);
                }
                var files = Directory.GetFiles(logFileDir).Where(p => p.EndsWith(".txt") || p.EndsWith(".log")).ToList();
                if (files != null && files.Count > 0)
                {
                    // 删除过期文件
                    var pathdueList = files.Where(f => DateTime.Now.Subtract(new FileInfo(f).CreationTime).TotalDays >= logFileExpireDay).ToList();
                    if (pathdueList != null && pathdueList.Count > 0)
                    {
                        foreach (var item in pathdueList)
                        {
                            File.Delete(item);
                            Logger.Info($"删除日志文件：{item}");
                        }
                    }
                }
                //每天执行一次
                await Task.Delay(TimeSpan.FromDays(1));
            }
        }
    }
}